package com.coderbean.demo.action;

import java.util.List;
import java.util.Optional;

import com.coderbean.demo.entity.UserModel;
import com.coderbean.demo.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;


@RestController
@RequestMapping("/user")
public class UserAction {
	
	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("list")
	public JSONObject list () {
		List<UserModel> userModels = userRepository.findAll();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("data", userModels);
		jsonObject.put("success", true);
		return jsonObject;
	}
	
	@DeleteMapping("{id}")
	public JSONObject delete (@PathVariable("id") Integer id) {
		userRepository.deleteById(id);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", true);
		return jsonObject;
	}
	
	@PostMapping("save")
	public JSONObject save(@RequestBody UserModel userModel) {
		userRepository.save(userModel);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", true);
		return jsonObject;
	}
	
	@PutMapping("{id}")
	public JSONObject edit (@PathVariable("id") Integer id, @RequestBody UserModel userModel) {
		Optional<UserModel> optional = userRepository.findById(id);
		if (optional.isPresent()) {
			UserModel old = optional.get();
			old.setNickname(userModel.getNickname());
			old.setUsername(userModel.getUsername());
			userRepository.save(old);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", true);
		return jsonObject;
	}

}
